<?php

namespace backend\controllers\system;

use backend\controllers\BaseController;
use backend\models\system\Admin;
use backend\models\system\Menu;
use Yii;
use backend\models\system\Auth;
use backend\models\system\search\AuthSearch;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AuthController implements the CRUD actions for Auth model.
 */
class AuthController extends BaseController
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Auth models.
     * @return mixed
     */
    public function actionIndex()
    {
        /* 添加当前位置到cookie供后续跳转调用 */
        $this->setForward();

        $searchModel = new AuthSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Auth model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Auth model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = $this->findModel(0);

        if (Yii::$app->request->isPost) {
            $postData = Yii::$app->request->post('Auth');
            $data = [
                'name' => $postData['name'],
                'description' => $postData['description'],
                'type' => Auth::TYPE_角色
            ];
            if ($model->load($data, '') && $model->save()) {
                $this->success('操作成功', $this->getForward());
            } else {
                $this->error(array_values($model->getFirstErrors())[0]);
            }
        }

        /* 模型默认值 */
        $model->loadDefaultValues();

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Auth model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        if ($id == '超级管理员') {
            $this->error('不能修改超级管理员');
        }

        $model = Auth::find()->where(['name'=>$id,'type'=>Auth::TYPE_角色])->one();

        if (Yii::$app->request->isPost) {
            $postData = Yii::$app->request->post('Auth');
            $data = [
                'name' => $postData['name'],
                'description' => $postData['description'],
                'type' => Auth::TYPE_角色
            ];
            if ($model->load($data,'') && $model->save()) {
                $this->success('操作成功', $this->getForward());
            } else {
                $this->error(array_values($model->getFirstErrors())[0]);
            }
        }


        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Auth model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $ids = array_unique(explode(',',$id));
        if (array_search('超级管理员',$ids)) {
            $this->error('不能删除超级管理员角色');
        }

        $model = $this->findModel(0);
        if ($this->delRow($model, 'name',$id)) {
            $this->success('删除成功', $this->getForward());
        } else {
            $this->error('删除失败！');
        }
    }

    /**
     * ---------------------------------------
     * 角色授权
     * ---------------------------------------
     */
    public function actionAuth($role)
    {
        /* 提交后 */
        if (Yii::$app->request->isPost) {
            $rules = Yii::$app->request->post('rules');
            /* 判断角色是否存在 */
            if (!$parent = Yii::$app->authManager->getRole($role)) {
                $this->error('角色不存在');
            }
            /* 删除角色所有child */
            Yii::$app->authManager->removeChildren($parent);

            if (is_array($rules)) {
                foreach ($rules as $rule) {
                    /* 更新auth_rule表 与 auth_item表 */
                    Yii::$app->authManager->saveRule($rule);
                    /* 更新auth_item_child表 */
                    Yii::$app->authManager->saveChild($parent->name, $rule);
                }
            }
            $this->success('更新权限成功', $this->getForward());
        }

        /* 获取栏目节点 */
        $node_list = Menu::returnNodes();
        $auth_rules = Yii::$app->authManager->getChildren($role);
        $auth_rules = array_keys($auth_rules);

        return $this->render('auth', [
            'node_list' => $node_list,
            'auth_rules' => $auth_rules,
            'role' => $role,
        ]);
    }

    /**
     * ---------------------------------------
     * 授权用户列表
     * ---------------------------------------
     */
    public function actionUser($role)
    {
        /* 添加当前位置到cookie供后续跳转调用 */
        $this->setForward();

        $uids = Yii::$app->authManager->getUserIdsByRole($role);
        $uids = implode(',', array_unique($uids));

        /*更新uids 为空的情况*/
        if ($uids) {
            $_where = 'uid in(' . $uids . ')';
        } else {
            $_where = '1 != 1';
        }

        return $this->render('user', [
            'dataProvider' => $this->lists1(new Admin(), $_where),
        ]);
    }

    /**
     * Finds the Auth model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Auth the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if ($id == 0) {
            return new Auth();
        }
        if (($model = Auth::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
